package com.example.blew.omp.system.service.impl;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.blew.omp.system.config.FileDirectory;
import com.example.blew.omp.system.mapper.FileMapper;
import com.example.blew.omp.system.model.converter.FileConverter;
import com.example.blew.omp.system.model.form.FileForm;
import com.example.blew.omp.system.model.po.File;
import com.example.blew.omp.system.service.FileService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, File> implements FileService {

    @Override
    public String upload(MultipartFile file, String fileName) {
        String path = FileDirectory.DIRECTORY + fileName;
        try {
            InputStream inputStream = file.getInputStream();
            writeFromStream(path,inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }

    @Override
    public String upload(InputStream inputStream, String fileName) {
        String path = FileDirectory.DIRECTORY + fileName;
        writeFromStream(path,inputStream);
        return path;
    }

    @Override
    public boolean save(FileForm fileForm) {
        File file = FileConverter.converterToPoByFrom(fileForm);
        return save(file);
    }

    public  boolean save(List<FileForm> fileForms){
        List<File> fileList = FileConverter.converterToPoByFrom(fileForms);
        return saveBatch(fileList);
    }

    protected void writeFromStream(String storePath, InputStream inputStream) {
        FileUtil.writeFromStream(inputStream, storePath);
    }
}
